package com.zhanghp.class039;

/**
 * 含有嵌套的字符串解码
 * 测试链接 : https://leetcode.cn/problems/decode-string/
 *
 * @author zhanghp
 * @since 2024/6/21 15:58
 */
public class Code02_DecodingString {

    public static int where;

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.setCharAt(0, '1');
        System.out.println(sb);
    }

    public String decodeString(String s) {
        where = 0;
        return f(s.toCharArray(), 0);
    }

    public String f(char[] c, int index) {
        StringBuilder sb = new StringBuilder();
        int repeatNum = 0;
        while (index < c.length && c[index] != ']') {

            // 字母处理
            if ((c[index] >= 'a' && c[index] <= 'z') || (c[index] >= 'A' && c[index] <= 'Z')) {
                sb.append(c[index++]);
            } else if (c[index] == '[') {
                // 嵌套处理
                // 数字 * 字母(嵌套后的结果)
                sb.append(repeatGet(repeatNum, f(c, index + 1)));
                repeatNum = 0;
                index = where + 1;
            } else {
                // 数字处理
                repeatNum = repeatNum * 10 + (c[index++] - '0');
            }
        }
        where = index;
        return sb.toString();
    }

    /**
     * 数字 * 字母，进行封装
     *
     * @param repeatNum 需要重复几次
     * @param str 字符串
     * @return 结果
     */
    public String repeatGet(int repeatNum, String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < repeatNum; i++) {
            sb.append(str);
        }
        return sb.toString();
    }
}
